package com.haohuo.utils;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson.JSONObject;
import com.haohuo.config.annotation.taskType;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 将注解对应的serviceBase 填充map。
 */
public class CptUtils {

    public static final String P_S_F_S_BEAN_LOCATION = "com.haohuo.bpm.beans";

    private volatile static Object mutex = new Object();

    public static <B> B getService(Map<String, B > serviceBaseMap,
                             Map<Integer, B > workidAndBeannames,
                             int dtType){
        B serviceBase = serviceBaseMap.get(dtType);
        if(serviceBase != null)
            return serviceBase;

        synchronized (mutex) {
            serviceBase = serviceBaseMap.get(dtType);
            if(serviceBase != null)
                return serviceBase;
            serviceBaseMap.forEach((key, value) -> {
                taskType annotation = AnnotationUtils.getAnnotation(value.getClass(), taskType.class);
                int type = annotation != null ? annotation.value() : 0;
                workidAndBeannames.put(type, value);
            });
            return workidAndBeannames.get(dtType);
        }
    }


    /**
     * 导出自定义实体
     * @param mapping
     * @return
     */
    public static List<ExcelExportEntity> buildExportCustomEntity(Map<String, JSONObject> mapping, List<?> dataSet) {

        Class<?> clazz;
        if(dataSet != null && !dataSet.isEmpty()){
            clazz = dataSet.get(0).getClass();
        }else{
            /* _12302_2021/7/25_< else块一般不会进来，此处添加是因为要初始化stream 中用到的clazz > */
            clazz = HashMap.class;
        }
        boolean isBean = clazz.getPackage().getName().indexOf(P_S_F_S_BEAN_LOCATION) != -1;

        List<String> fields;
        if(isBean){ fields = Arrays.stream(clazz.getDeclaredFields())
                .map(field -> field.getName()).collect(Collectors.toList());}
        else{ fields = null;}

        List<ExcelExportEntity> collect = mapping.entrySet().stream()
                .filter((entry) -> {
                    /* _12302_2021/7/25_< 过滤掉实体里面没有还想导出的属性 > */
                    if (isBean) {
                        return fields.contains(entry.getKey());
                    }
                    return !"_global_".equals(entry.getKey());
                })
                .map(entry -> {
                    String key = entry.getKey();
                    JSONObject value = entry.getValue();
                    ExcelExportEntity column = new ExcelExportEntity(value.getString("header"), key);
                    if(value.getInteger("width") != null){column.setWidth(value.getInteger("width"));}
                    if(value.getInteger("orderNum") != null){column.setOrderNum(value.getInteger("orderNum"));}
                    if(value.getString("groupName") != null){column.setGroupName(value.getString("groupName"));}
                    if (isBean) {
                        try {
                            column.setMethod(clazz.getMethod(acquireGetName(key)));
                        } catch (NoSuchMethodException e) { /* _12302_2021/7/25_< ignore ... > */ }
                    }
                    return column;
                })
                .collect(Collectors.toList());

        return collect;
    }

    private static String acquireGetName(String field){
        char[] chars = field.toCharArray();
        chars[0] = (char)(chars[0] - 32);
        return "get" + String.valueOf(chars);
    }

}
